﻿using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CSharpWheels.Librarys.Dump
{
    public class MiniDump
    {
        [DllImport("dbghelp.dll", SetLastError = true)]
        protected static extern bool MiniDumpWriteDump(
            IntPtr hProcess,
            uint processId,
            SafeFileHandle hFile,
            uint dumpType,
            IntPtr expParam,
            IntPtr userStreamParam,
            IntPtr callbackParam);


        public static void Create(string dumpFilePath)
        {
            Create(dumpFilePath, MiniDumpType.MiniDumpWithFullMemory);
        }
        public static void Create(string dumpFilePath, MiniDumpType miniDumpType)
        {
            using (var fs = new FileStream(dumpFilePath, FileMode.Create))
            {
                var currentProcess = Process.GetCurrentProcess();
                var processHandle = currentProcess.Handle;
                var processId = (uint)currentProcess.Id;

                bool success = MiniDumpWriteDump(
                    processHandle,
                    processId,
                    fs.SafeFileHandle,
                    (uint)miniDumpType,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    IntPtr.Zero);

                if (!success)
                {
                    throw new System.ComponentModel.Win32Exception(
                        Marshal.GetLastWin32Error());
                }
            }
        }
    }

    [Flags]
    public enum MiniDumpType : uint
    {
        MiniDumpNormal = 0x00000000,
        MiniDumpWithDataSegs = 0x00000001,
        MiniDumpWithFullMemory = 0x00000002,
        MiniDumpWithHandleData = 0x00000004,
        // 其他标志...
    }
}
